import axios from 'axios';
import { sm2 } from 'sm-crypto';
import { auth } from './settings';

/**
 * sm2 加密方法
 * @param data
 * @returns {*}
 */
const encrypt = (data) => {
    try {
        return sm2.doEncrypt(data, auth.publicKey, 0);
    } catch {
        return '';
    }
};

const isChinese = (s) => {
	return /[\u4e00-\u9fa5]/.test(s);
};

const utils = {
    integerRandom: (lower, upper) => {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    },
    isNull: (obj) => {
        return obj === undefined || obj === null;
    },
    isEmpty: (str) => {
        return str === undefined || str === null || str.length === 0;
    },
    unicodeToChinese: (unicodeStr) => {
        return unicodeStr.replace(/\\u[\dA-F]{4}/gi, function(match) {
            return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
        });
    },
    chinese2Unicode: (str) => {
        if(!str){
            return;
        }
        var unicode = '';
        for (var i = 0; i <  str.length; i++) {
            var temp = str.charAt(i);
            if(isChinese(temp)){
                unicode += '\\u' +  temp.charCodeAt(0).toString(16);
            }
            else{
                unicode += temp;
            }
        }
        return unicode;
    },
    downloadFile: (url, fileName) => {
        axios.get(url, { responseType: 'blob' })
        .then(response => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
        })
        .catch(error => {
          console.error(error);
        });
    },
    encrypt
};

export default utils;